package com.ffs.template.util;

/**
 * 字符工具
 *
 * @author ffs80
 */
@SuppressWarnings("unused")
public class StringUtil {
    /**
     * 下划线转驼峰
     */
    public static String switchField(String str) {
        if (str == null || "".equals(str)) {
            return "";
        }
        str = str.toLowerCase();

        String[] split = str.split("_");
        if (split.length == 1) {
            return split[0];
        }
        StringBuilder builder = new StringBuilder(split[0]);
        for (int i = 1; i < split.length; i++) {
            builder.append(captureName(split[i]));
        }
        return builder.toString();
    }

    /**
     * 表名转换
     *
     * @param tableName 表名
     * @return java对象名
     */
    public static String switchTableName(String tableName) {
        if (tableName == null || "".equals(tableName)) {
            return "";
        }

        tableName = tableName.toLowerCase();

        String[] split = tableName.split("_");
        if (split.length == 1) {
            return captureName(split[0]);
        }

        StringBuilder builder = new StringBuilder(captureName(split[0]));
        for (int i = 1; i < split.length; i++) {
            builder.append(captureName(split[i]));
        }
        return builder.toString();
    }

    /**
     * 数据库类型与java类型进行转换
     * TODO：不完善
     * @param type 数据库类型
     */
    public static String typeSwitch(String type) {
        String javaType = "";
        switch (type) {
            case "bigint":
                javaType = "long";
                break;
            case "varchar":
            case "char":
            case "datetime":
            case "text":
            case "decimal":
                javaType = "String";
                break;
            case "int":
                javaType = "int";
                break;
            default:
        }
        return javaType;
    }

    /**
     * 字符串首字母大写
     *
     * @param str 字符串
     */
    private static String captureName(String str) {
        // 进行字母的ascii编码前移，效率要高于截取字符串进行转换的操作
        char[] cs = str.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }
}
